import { ElLoading } from "element-plus"
import http from "@/utils/http"
import { nextTick, Ref } from "vue-demi"
import { useStore } from "@/store/index"
import { FileItemType } from "../type"

interface ParamsType {
  getExpandedList: () => void
  treeHoverId: Ref<number | null>
}

function useSelect({ getExpandedList, treeHoverId }: ParamsType) {
  const store = useStore()
  // 获取文档内容详情
  const getMarkdown = async (id: number) => {
    const editorDom = document.querySelector(".editor-container")
    const loadingInstance = ElLoading.service({
      target: editorDom as HTMLElement,
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(255, 255, 255, 0.3)",
    })
    const res = await http.get("/file/getMarkdown", { id })
    if (res.code === 1) {
      store.commit("markdown/setMarkdown", res.data)
      nextTick(() => {
        loadingInstance.close()
      })
    }
  }
  // 树节点点击事件
  const nodeClick = (data: FileItemType) => {
    if (!data.isDir) {
      store.commit("fileTree/switchFileTree", false)
      getMarkdown(data.id)
    } else {
      getExpandedList()
    }
  }

  // 切换右键选中框
  const changeHover = (flag: boolean, id: number) => {
    if (flag) {
      treeHoverId.value = id
    } else {
      treeHoverId.value = null
    }
  }

  return { nodeClick, changeHover }
}

export default useSelect
